package com.ybkj.o2o.zhuanche.common.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.o2o.zhuanche.controller.v4.ErrorConstantV4;
import com.ybkj.o2o.zhuanche.controller.v4.ResultTransport;
import com.ybkj.o2o.zhuanche.entity.ChargeStartTime;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DaijiaApi {
  @Autowired
  private RestTemplate restTemplate;

  // 还有未完成支付的订单，不能下单
  public static final String COUNT_NOTPAY_ORDERS = "api/passenger/v4/countNotPayOrders?passengerId={passengerId}";
  // 查询配置信息
  public static final String APP_SETTING = "api/system/getAppSetting";
  //
  public static final String YUYUE_SETTING = "/api/system/getYuyueSetting";
  /**
   * 统计未支付.
   * @param server 服务器地址
   * @param passengerId 乘客id
   * @return 未支付订单数量.
   */
  
  public Long countNotPayAmounts(String server, Long passengerId) {
    Long num = 0L;
    try {
      Map<String, String> kv = new HashMap<String, String>();
      StringBuilder builder = new StringBuilder();
      builder.append(buildApi(server, COUNT_NOTPAY_ORDERS));
      kv.put("passengerId", String.valueOf(passengerId));
      String result = restTemplate.getForObject(builder.toString(), String.class, kv);
      ResultTransport orderTransport = JSON.parseObject(result, ResultTransport.class);
      if (orderTransport.getCode() == 0) {
        num = Long.valueOf(orderTransport.getData().toString());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return num;
  }
  /**
   * 查询后台设置.
   * @param server 服务器地址.
   * @return 是否专车需要预付费.
   */
  
  public Boolean findErrandSetting(String server) {
    try {
      String response = restTemplate.getForObject(buildApi(server, APP_SETTING), String.class);
      JSONObject jsonObject = JSON.parseObject(response);
      Boolean zhuanchePrePay = jsonObject.getBooleanValue("zhuanchePrePay");
      return zhuanchePrePay;
    } catch (Exception ex) {
      ex.printStackTrace();
      return Boolean.FALSE;
    }
  }
  /**
   * 查询后台设置.
   * @param server 服务器地址.
   * @return 后台设置的预约时间分钟数
   */

  public Long findYuyueTimeSetting(String server) {
    try {
      String response = restTemplate.getForObject(buildApi(server, APP_SETTING), String.class);
      JSONObject jsonObject = JSON.parseObject(response);
      Long zhuanchePrePay = jsonObject.getLongValue("yuyueTime");
      return zhuanchePrePay*60*1000;
    } catch (Exception ex) {
      ex.printStackTrace();
      return 0l;
    }
  }
  
  /**
   * 查询后台设置.
   * @param server 服务器地址.
   * @return 后台设置的预约时间分钟数
   */

  public Long findZhuanYuyueSetting(String server) {
    try {
      String response = restTemplate.getForObject(buildApi(server, APP_SETTING), String.class);
      JSONObject jsonObject = JSON.parseObject(response);
      Long zhuanchePrePay = jsonObject.getLongValue("zhuanYuyue");
      return zhuanchePrePay*60*1000;
    } catch (Exception ex) {
      ex.printStackTrace();
      return 0l;
    }
  }
  
  /**
   * 查询后台设置.
   * @param server 服务器地址.
   * @return 后台设置的预约最大单量
   */
  public Long findYuyueMaxSetting(String server) {
    try {
      String response = restTemplate.getForObject(buildApi(server, APP_SETTING), String.class);
      JSONObject jsonObject = JSON.parseObject(response);
      Long zhuanYuyueMax = jsonObject.getLongValue("yuyueMax");
      return zhuanYuyueMax;
    } catch (Exception ex) {
      ex.printStackTrace();
      return 0l;
    }
  }
  
  
  /**
   * 获取微信,支付宝,银联支付信息是否配置好.
   */
  public Map<String, Object> queryPaySetting(String address) {
    Map<String, Object> map = new HashMap<String, Object>();
    StringBuilder builder = new StringBuilder();
    builder.append(buildApi(address, "api/system/queryPaySetting.json"));
    String result = restTemplate.getForObject(builder.toString(), String.class);
    JSONObject jsonObject = JSON.parseObject(result);

    Boolean success = jsonObject.getBoolean("success");
    if (success) {
      Boolean weixinPay = jsonObject.getBoolean("weixinPay");
      Boolean aliPay = jsonObject.getBoolean("aliPay");
      try {
        Boolean unionPay = jsonObject.getBoolean("unionPay");
        map.put("unionPay", unionPay);
      } catch (Exception e) {
        e.printStackTrace();
        map.put("unionPay", Boolean.FALSE);
      }
      map.put("weixinPay", weixinPay);
      map.put("aliPay", aliPay);
    } else {
      map.put("weixinPay", Boolean.FALSE);
      map.put("aliPay", Boolean.FALSE);
      map.put("unionPay", Boolean.FALSE);
    }
    return map;
  }

  /**
   * 查询服务人员.
   */
  public Map<String, Object> queryDriver(String address, Long driverId) {
    Map<String, Object> map = new HashMap<String, Object>();
    StringBuilder builder = new StringBuilder();
    builder.append(buildApi(address, "api/daijia/queryDriver.json?driverId={driverId}"));
    String result = restTemplate.getForObject(builder.toString(), String.class, driverId);
    JSONObject jsonObject = JSON.parseObject(result);
    Boolean success = jsonObject.getBoolean("success");
    if (success) {
      Long employId = jsonObject.getLong("employId");
      String employName = jsonObject.getString("employName");
      String employAccount = jsonObject.getString("employAccount");
      String employPhone = jsonObject.getString("employPhone");
      String employPhoto = jsonObject.getString("employPhoto");
      Long companyId = jsonObject.getLong("companyId");
      String companyName = jsonObject.getString("companyName");
      String message = jsonObject.getString("message");
      Double employScore = jsonObject.getDouble("employScore");
      Integer status = jsonObject.getInteger("status");
      map.put("employId", employId);
      map.put("employName", employName);
      map.put("employNo", employAccount);
      map.put("employPhone", employPhone);
      map.put("employPhoto", employPhoto);
      map.put("employCompanyId", companyId);
      map.put("employCompanyName", companyName);
      map.put("employScore", employScore);
      map.put("status", status);
      map.put("message", message);
      map.put("success", Boolean.TRUE);
    } else {
      map.put("success", Boolean.FALSE);
      map.put("message", jsonObject.getString("message"));
    }
    return map;
  }
  public Map<String, Object> queryCountRunning(String address, Long passengerId) {
    Map<String, Object> map = new HashMap<String, Object>();
    StringBuilder builder = new StringBuilder();
    builder.append(buildApi(address, "passenger/api/rest/v4up/queryPassengerUnFinishOrder.json?passengerId={passengerId}"));
    String result = restTemplate.getForObject(builder.toString(), String.class, passengerId);
    JSONObject jsonObject = JSON.parseObject(result);
    Integer code = jsonObject.getInteger("code");
    if (null != code) {
      map.put("code", jsonObject.getInteger("code"));
    } else {
      map.put("code", -86);
    }
    return map;
  }

  /**
   * 查询司机是否忙碌.
   * @param server 服务器地址.
   * @param driverId success:true/false 访问失败:false status:0:未上班,1:空闲(在线),2:接单,3:忙碌 jobStatus:0代驾 1专车
   *        2跑腿 -1无任务
   * @return true可以接单,false不可以接单.
   */
  public boolean findEmployStatus(String server, Long driverId) {
    boolean bool = false;
    try {

      StringBuilder builder = new StringBuilder();
      builder.append(buildApi(server, "api/errand/getEmployStatus"));
      builder.append("?driverId={driverId}");
      String response = restTemplate.getForObject(builder.toString(), String.class, driverId);

      JSONObject jsonObject = JSON.parseObject(response);

      boolean success = jsonObject.getBoolean("success");
      if (success == true) {
        int status = jsonObject.getIntValue("status"); // 工作状态
        int jobStatus = jsonObject.getIntValue("jobStatus"); // 执行类型
        if ((jobStatus == 1 || jobStatus == -1) && status == 1) {
          bool = true;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return bool;
  }
  /**
   * 查询收费标准.
   * @param serverUrl 服务器地址.
   * @param areaId 地区收费id.
   * @return 收费标准.
   */
  
  public List<ChargeStartTime> findChargeStartTimes(String serverUrl, Long areaId) {
    List<ChargeStartTime> chargeStartTimes = new ArrayList<ChargeStartTime>();
    try {
      if (areaId != null) {
        StringBuilder builder2 = new StringBuilder();
        builder2.append(buildApi(serverUrl,
            "api/company/v4/findChargeStartTimes.json?areaId={areaId}"));
        String result2 = restTemplate.getForObject(builder2.toString(), String.class, areaId);
        ResultTransport areaTransport = JSON.parseObject(result2, ResultTransport.class);

        if (areaTransport.getCode() == 0) {
          chargeStartTimes =
              JSON.parseArray(areaTransport.getData().toString(), ChargeStartTime.class);
        }
      }
    } catch (RestClientException e) {
      e.printStackTrace();
    }
    return chargeStartTimes;
  }
  
  /**
   * 查询地区收费名称.
   * @param serverUrl 服务器地址.
   * @param areaId 地区收费id.
   * @return 收费标准.
   */
  
  public String findAreaName(String serverUrl, Long areaId) {
    String areaName = "";
    try {
      if (areaId != null) {
        StringBuilder builder2 = new StringBuilder();
        builder2.append(buildApi(serverUrl,
            "api/company/v4/findAreaName.json?areaId={areaId}"));
        String result2 = restTemplate.getForObject(builder2.toString(), String.class, areaId);
        ResultTransport areaTransport = JSON.parseObject(result2, ResultTransport.class);

        if (areaTransport.getCode() == 0) {
          areaName = areaTransport.getData().toString();
        }
      }
    } catch (RestClientException e) {
      e.printStackTrace();
    }
    return areaName;
  }
  
  public ResultTransport queryVoiceState(String serverUrl, Long voiceId) {
    try {
        StringBuilder builder = new StringBuilder();
        builder.append(buildApi(serverUrl, "api/panggilmobil/queryVoiceState?voiceId={voiceId}"));
        String result = restTemplate.getForObject(builder.toString(), String.class, voiceId);
        ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);
        return resultTransport;
    } catch (RestClientException e) {
      e.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  public void updateVoiceState(String serverUrl, Long voiceId, Long orderId, String orderNo) {
    try {
      if (null != voiceId && null != orderId  && StringUtils.isNotBlank(orderNo)) {
        StringBuilder builder = new StringBuilder();
        builder.append(buildApi(serverUrl, 
            "api/panggilmobil/updateVoiceState?voiceId={voiceId}&orderId={orderId}&orderNo={orderNo}"));
        restTemplate.getForObject(builder.toString(), String.class, voiceId,orderId,orderNo);
      }
    } catch (RestClientException e) {
      e.printStackTrace();
    }
  }
  
  public JSONObject getYuyueSetting(String address) { 
	  JSONObject yuyueSetting = JSONObject.parseObject(restTemplate.getForEntity(buildApi(address, YUYUE_SETTING), 
			  String.class).getBody());
	  return yuyueSetting; 
  } 

  /**
   * 构建地址.
   */
  private String buildApi(String server, String api) {

    StringBuilder builder = new StringBuilder();

    String daijiaServer = StringUtils.trimToEmpty(server).toLowerCase();
    if (!daijiaServer.startsWith("http://") && !daijiaServer.startsWith("https://")) {
      builder.append("http://");
    }

    builder.append(daijiaServer);
    if (!daijiaServer.endsWith("/")) {
      builder.append("/");
    }

    if (StringUtils.isNotBlank(api)) {
      builder.append(api);
    }

    return builder.toString();
  }

}
